import './organization.less';
import { useState, useEffect, useRef } from 'react';
import { OrganizationTree } from './organization-tree';
import { flatTree, INodeStruct } from 'spd-components/tree';
import { IEnterpriseStruct } from 'spd-request/organization-unit';
import { UserList } from './user-list';


// function  useAddEnterpriceForm(changeAddFormStatus: any) {
//     function addDepartment(data: any) {
        
//     }
//     const AddForm = <EnterpriseForm.Add onCancel={changeAddFormStatus}  onSuccessAdd={addDepartment} changeVisualStatus={changeAddFormStatus}></EnterpriseForm.Add>;
// }

export default function Origanization() {

    let userListRef = useRef();
    let organizitionRef: any = useRef();
    let [activeTreeNode, setActiveTreeNode] = useState<INodeStruct<IEnterpriseStruct>|null>(null);
    let [treeOriginData, setTreeOriginData] = useState<INodeStruct<IEnterpriseStruct>[]>([]);

    useEffect(() => {
        let ids: number[] = [];
        if(activeTreeNode ==  null) {
            treeOriginData.forEach(element => {
                ids.push(element.id);
            });
        } else {
            let datas = flatTree<{id: number}>(activeTreeNode);
            datas.forEach(element => {
                ids.push(element.data.id)
            });
        }
        // @ts-ignore
        userListRef.current.changeDepartmentIds(ids);
    }, [
        activeTreeNode,
        treeOriginData
    ]);

    function treeDataChange() {
        if(organizitionRef?.current?.getActiveNode() !== activeTreeNode) {
            setActiveTreeNode(organizitionRef?.current?.getActiveNode());
        }
        if(organizitionRef?.current?.getOriginData() !== treeOriginData) {
            setTreeOriginData(organizitionRef?.current?.getOriginData());
        }
    }

    return (
        <>
            <div className="organization-container">
                <div className="tree-container">
                    <OrganizationTree ref={organizitionRef} onActiveNodeChange={treeDataChange} onDataChcange={treeDataChange}/>
                </div>
                <div className="user-table-content">
                    <UserList ref={userListRef}></UserList>
                </div>
            </div>
        </>
    );
}